<?php

/**
 * Url
 *
 * @author coder_
 */

class Url extends _Module
{
    private static $instance;

    private $dependencies = array('Config');
    private $host;
    private $query_string;
    private $uri;
    private $uri_string;

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    public static function &getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    public function initialize()
    {
        $this->host = $_SERVER['HTTP_HOST'];
        $this->query_string = $_SERVER['QUERY_STRING'];
        $request_uri = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
        $request_uri = array_filter($request_uri, array($this, 'filterRequestUri'));


        $request_url = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://' . $this->host . $_SERVER['REQUEST_URI'];

        $own_url = getModule('Config')->setType($request_url);

        $own_url = preg_replace('/^([(http)(https)])+:\/\//i', '', $own_url);
        $slashpos = strpos($own_url, '/');
        $own_url = substr($own_url, $slashpos);

        $own_url = array_filter(explode('/', $own_url));

        $request_uri = array_values(array_diff($request_uri, $own_url));



        $this->uri = $request_uri;
        $this->createUriString();
    }

    public function getDependencies()
    {
        return $this->dependencies;
    }

    public function getHost()
    {
        return $this->host;
    }

    public function getQueryString()
    {
        return $this->query_string;
    }

    public function getUri()
    {
        return $this->uri_string;
    }

    public function getUriArray()
    {
        return $this->uri;
    }

    public function setUriArray($uri =  array())
    {
        $this->uri = $uri;
        $this->createUriString();
    }

    public function get($number)
    {
        if (isset($this->uri[$number])) return strtolower($this->uri[$number]);
        else return '';
    }

    public function reload()
    {
        header('location:' . URL . $this->uri_string);
        dump(URL . $this->uri_string);
    }

    private function createUriString()
    {
        if(count($this->uri) == 0)
        {
            $this->uri_string = '/';
        } else {
            $this->uri_string = '/' . join('/', $this->uri) . '/';
        }
    }

    private function filterRequestUri($var)
    {
        if(strpos($var, '?') === false) return true;
    }
}